package se_report

import (
	"fmt"
	"strconv"
	"strings"
	"time"
	"wx-api/ssp-api/cache"
	"wx-api/ssp-api/config"
	"wx-api/ssp-api/errmsg"
	"wx-api/ssp-api/handlers"
	"wx-api/ssp-api/services/comm"
	"wx-api/ssp-api/utils"
)

type YmapStruct struct {
	Req   int64
	Fill  int64
	View  int64
	Click int64
	Dp    int64
	Price float64
}

func SspReportIndex(c *handlers.Controller) {
	ssp_uid := comm.GetUserInfo(c)
	if ssp_uid == "" {
		return
	}
	sql := "select date,sum(req) as req,sum(fill) as fill, " +
		"sum(pv) as pv, sum(ipv) as ipv, sum(click) as click, sum(iclick) as iclick, " +
		"sum(deeplink) as deeplink,sum(ideeplink) as ideeplink,sum(adx_price) as adx_price " +
		"from " + config.CkTableSspReport
	where := " where adx_id='" + ssp_uid + "'"
	Sdate := time.Now().Format("2006-01-02")
	Edata := time.Now().AddDate(0, 0, -30).Format("2006-01-02")
	where += " and date >='" + Edata + "' and date <= '" + Sdate + "'"
	sql = sql + where + " group by date"
	ret := []SspCkReport{}
	err := config.CKDB.Select(&ret, sql)
	if err != nil {
		fmt.Println("select error:" + err.Error())
		return
	}
	yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	semday := time.Now().AddDate(0, 0, -7).Format("2006-01-02")
	ymap := map[string]YmapStruct{
		time.Now().AddDate(0, 0, 0).Format("2006-01-02"):  YmapStruct{},
		time.Now().AddDate(0, 0, -1).Format("2006-01-02"): YmapStruct{},
		time.Now().AddDate(0, 0, -2).Format("2006-01-02"): YmapStruct{},
		time.Now().AddDate(0, 0, -3).Format("2006-01-02"): YmapStruct{},
		time.Now().AddDate(0, 0, -4).Format("2006-01-02"): YmapStruct{},
		time.Now().AddDate(0, 0, -5).Format("2006-01-02"): YmapStruct{},
		time.Now().AddDate(0, 0, -6).Format("2006-01-02"): YmapStruct{},
	}
	sumd := float64(0)
	sums := float64(0)
	summ := float64(0)
	semdayint := utils.DecDate(semday)
	for _, val := range ret {
		ddd := val.Date[0:10]
		dddint := utils.DecDate(ddd)
		summ += val.AdxPrice  //30日
		if ddd == yesterday { //昨日
			sumd += val.AdxPrice
		}
		if semdayint <= dddint { //7日
			sums += val.AdxPrice
		}
		tmpy, ok := ymap[ddd]
		if ok {
			tmpy.Req += val.Req
			tmpy.Fill += val.Fill
			tmpy.View += val.Pv
			tmpy.Click += val.Click
			tmpy.Dp += val.Deeplink
			tmpy.Price += val.AdxPrice
		}
	}
	retdata := map[string]interface{}{
		"sumobj": map[string]interface{}{
			"sumd": utils.Decimal(sumd / 100000),
			"sums": utils.Decimal(sums / 100000),
			"summ": utils.Decimal(summ / 100000),
		},
	}
	x := []string{
		time.Now().AddDate(0, 0, -6).Format("2006-01-02"),
		time.Now().AddDate(0, 0, -5).Format("2006-01-02"),
		time.Now().AddDate(0, 0, -4).Format("2006-01-02"),
		time.Now().AddDate(0, 0, -3).Format("2006-01-02"),
		time.Now().AddDate(0, 0, -2).Format("2006-01-02"),
		time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
		time.Now().AddDate(0, 0, 0).Format("2006-01-02"),
	}
	retdata["x"] = x
	retdata["y"] = SspReportIndexY(x, ymap)
	c.SetErrorMsg(retdata, errmsg.SuccessMsg())
	return
}

func SspReportIndexY(x []string, y map[string]YmapStruct) interface{} {
	y_req := make([]int64, len(x))
	y_fill := make([]int64, len(x))
	y_view := make([]int64, len(x))
	y_click := make([]int64, len(x))
	y_dp := make([]int64, len(x))
	y_price := make([]float64, len(x))
	for _, s := range x {
		tmp, ok := y[s]
		if ok {
			y_req = append(y_req, tmp.Req)
			y_fill = append(y_fill, tmp.Fill)
			y_view = append(y_view, tmp.View)
			y_click = append(y_click, tmp.Click)
			y_dp = append(y_dp, tmp.Dp)
			y_price = append(y_price, utils.Decimal(tmp.Price/100000))
		}
	}
	return []interface{}{
		y_req, y_fill, y_view, y_click, y_dp, y_price,
	}
}

type ParamReport struct {
	Sdate    string   `form:"stime" json:"stime"`
	Edata    string   `form:"etime" json:"etime"`
	Grp      string   `form:"grp" json:"grp"`
	Mids     []string `form:"media_ids" json:"media_ids"`
	SlotIds  []string `form:"slot_ids" json:"slot_ids"`
	Page     int64    `form:"page" json:"page"`
	PageSize int64    `form:"page_size" json:"page_size"`
}

func SspReport(c *handlers.Controller) {
	var form ParamReport
	if err := c.Ctx.ShouldBind(&form); err != nil {
		fmt.Println(err)
		c.BadRequest()
		return
	}
	ssp_uid := comm.GetUserInfo(c)
	if ssp_uid == "" {
		return
	}
	if form.Page == 0 {
		form.Page = 1
	}
	if form.PageSize == 0 {
		form.PageSize = 50
	}
	if form.Sdate == "" {
		form.Sdate = time.Now().Format("2006-01-02")
	}
	if form.Edata == "" {
		form.Edata = time.Now().Format("2006-01-02")
	}
	sql := "select date,adx_id,media_id,slot_id,sum(req) as req,sum(fill) as fill, " +
		"sum(pv) as pv, sum(ipv) as ipv, sum(click) as click, sum(iclick) as iclick, " +
		"sum(deeplink) as deeplink,sum(ideeplink) as ideeplink,sum(adx_price) as adx_price " +
		"from " + config.CkTableSspReport
	where := " where adx_id='" + ssp_uid + "'"
	if form.Sdate == form.Edata {
		where += " and date ='" + form.Sdate + "'"
	}
	if form.Sdate != form.Edata {
		where += " and date >='" + form.Edata + "' and date <= '" + form.Sdate + "'"
	}
	if len(form.Mids) > 0 {
		where += " and media_id in ('" + strings.Join(form.Mids, "','") + "')"
	}
	if len(form.SlotIds) > 0 {
		where += " and slot in ('" + strings.Join(form.SlotIds, "','") + "')"
	}
	order := " order by date desc"
	group := " group by adx_id,media_id,slot_id"
	if form.Grp == "1" {
		group += ",date,date_hour"
		order = " order by date,date_hour desc"
	} else {
		group += ",date"
	}
	limitto := (form.Page - 1) * form.PageSize
	limitfo := form.PageSize
	limit := " limit " + strconv.Itoa(int(limitto)) + "," + strconv.Itoa(int(limitfo))
	//获取总页数
	count := config.GetCkCount(config.CkTableSspReport + where + group)
	retd := config.DataList{
		PageSize: form.PageSize,
		PageNum:  form.Page,
		Total:    count,
	}

	sql = sql + where + group + order + limit
	ret := []SspCkReport{}
	err := config.CKDB.Select(&ret, sql)
	if err != nil {
		fmt.Println("select error:" + err.Error())
		return
	}
	for i, val := range ret {
		if val.Fill == 0 && val.Pv == 0 && val.Ipv == 0 {
			continue
		}
		appinfo, ok := cache.CacheSspAppMapNGet(val.MediaId)
		if ok {
			val.MediaName = appinfo.Name
		} else {
			val.MediaName = "-"
		}
		slotinfo, ok := cache.CacheSspSlotMapNGet(val.SlotId)
		if ok {
			val.SlotName = slotinfo.Name
		} else {
			val.SlotName = "-"
		}
		val.Date = val.Date[0:10]
		val.AdxPrice = utils.Decimal(val.AdxPrice / 100000)
		ret[i] = val
	}
	retd.List = ret
	c.SetErrorMsg(retd, errmsg.SuccessMsg())
	return
}

type SspCkReport struct {
	Date      string  `db:"date" json:"date" bson:"date"`
	DateHour  string  `db:"date_hour" json:"date_hour" bson:"date_hour"`
	AdxId     string  `db:"adx_id" json:"adx_id" bson:"adx_id"`
	AdxName   string  `db:"_" json:"adx_name" bson:"adx_name"`
	MediaId   string  `db:"media_id" json:"media_id" bson:"media_id"`
	MediaName string  `db:"_" json:"media_name" bson:"media_name"`
	SlotId    string  `db:"slot_id" json:"slot_id" bson:"slot_id"`
	SlotName  string  `db:"_" json:"slot_name" bson:"slot_name"`
	Req       int64   `db:"req" json:"req" bson:"req"`
	Fill      int64   `db:"fill" json:"fill" bson:"fill"`
	Pv        int64   `db:"pv" json:"pv" bson:"pv"`
	Ipv       int64   `db:"ipv" json:"ipv" bson:"ipv"`
	Click     int64   `db:"click" json:"click" bson:"click"`
	Iclick    int64   `db:"iclick" json:"iclick" bson:"iclick"`
	Deeplink  int64   `db:"deeplink" json:"deeplink" bson:"deeplink"`
	Ideeplink int64   `db:"ideeplink" json:"ideeplink" bson:"ideeplink"`
	AdxPrice  float64 `db:"adx_price" json:"adx_price" bson:"adx_price"`
}
